<template>
  <el-dialog v-model="dialogOptions.visible" :title="dialogTitle" width="1450px" append-to-body custom-class="flat-form-dialog">
    <el-form
      ref="houseFormRef"
      v-loading="dialogOptions.loading"
      :disabled="dialogOptions.type === 'view' || dialogOptions.type === 'history'"
      :rules="formRules"
      :model="data"
      label-width="110px"
    >
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>基础信息</h2>
      </div>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="原&nbsp;&nbsp;单&nbsp;&nbsp;位" prop="basicInfo.primarySinglet">
            <el-input v-model="data.basicInfo.primarySinglet" placeholder="请输入原单位" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房产名称" prop="basicInfo.propertyName">
            <el-input v-model="data.basicInfo.propertyName" placeholder="请输入房产名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房产位置" prop="basicInfo.propertyLocation">
            <el-input v-model="data.basicInfo.propertyLocation" placeholder="请输入房产位置" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="门&nbsp;&nbsp;牌&nbsp;&nbsp;号" prop="basicInfo.doorNumber">
            <el-input v-model="data.basicInfo.doorNumber" placeholder="请输入房间号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="建筑面积(㎡)" prop="basicInfo.floorArea">
            <el-input v-model="data.basicInfo.floorArea" placeholder="请输入建筑面积(㎡)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="不动产登记号" prop="basicInfo.realEstateRegistrationNumber">
            <el-input v-model="data.basicInfo.realEstateRegistrationNumber" placeholder="请输入不动产登记号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="租赁状况" prop="basicInfo.leaseStatus">
            <el-select v-model="data.basicInfo.leaseStatus" placeholder="请选择租赁状态" :disabled="originalLeaseStatus === 'leased'">
              <el-option v-for="dict in parkbuilingroom_state" :key="`room_state_${dict.label}`" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;类" prop="basicInfo.type">
            <el-input v-model="data.basicInfo.type" placeholder="请输入分类" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房产估值" prop="basicInfo.propertyValuation">
            <el-input v-model="data.basicInfo.propertyValuation" placeholder="请输入房产估值" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="备注" prop="basicInfo.attachments">
            <file-upload v-model="data.basicInfo.attachments" placeholder="请上传公寓附件" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租赁附件" prop="rentalInfo.attachments">
            <file-upload v-model="data.rentalInfo.attachments" placeholder="请上传租赁附件" />
          </el-form-item>
        </el-col> -->
      </el-row>
      <div v-if="data.basicInfo.leaseStatus === 'leased' || dialogOptions.type == 'history'" class="kuaicenter">
        <div class="kuai"></div>
        <h2>租赁信息</h2>
      </div>
      <el-row v-if="data.basicInfo.leaseStatus === 'leased' || dialogOptions.type == 'history'" :gutter="24">
        <el-col :span="6">
          <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="rentalInfo.name">
            <el-input v-model="data.rentalInfo.name" placeholder="请输入承租人" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联&nbsp;&nbsp;系&nbsp;&nbsp;人" prop="rentalInfo.associate">
            <el-input v-model="data.rentalInfo.associate" placeholder="请输入承租人" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式" prop="rentalInfo.contactInformation">
            <el-input v-model="data.rentalInfo.contactInformation" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="承租面积(㎡)" prop="rentalInfo.leaseholdArea">
            <el-input v-model="data.rentalInfo.leaseholdArea" placeholder="请输入承租面积(㎡)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同期限" prop="rentalInfo.termContract">
            <el-input v-model="data.rentalInfo.termContract" placeholder="请输入合同期限" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开始日期" prop="rentalInfo.startTime">
            <el-date-picker v-model="data.rentalInfo.startTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束日期" prop="rentalInfo.endTime">
            <el-date-picker v-model="data.rentalInfo.endTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="剩余天数" prop="rentalInfo.remainingDays">
            <el-input v-model="data.rentalInfo.remainingDays" placeholder="请输入剩余天数" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同编号" prop="rentalInfo.contractNumber">
            <el-input v-model="data.rentalInfo.contractNumber" placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="租金规定" prop="rentalInfo.rentRegulation">
            <el-input v-model="data.rentalInfo.rentRegulation" placeholder="请输入租金规定" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="缴租频次" prop="rentalInfo.frentPaymentFrequency">
            <el-select v-model="data.rentalInfo.frentPaymentFrequency" placeholder="请选择缴租频次">
              <el-option
                v-for="dict in park_frent_payment_frequency"
                :key="`frent_payment_frequency_${dict.label}`"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="评估年租金" prop="rentalInfo.appraisedAnnualRent">
            <el-input v-model="data.rentalInfo.appraisedAnnualRent" placeholder="请输入评估年租金" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="折合日租金" prop="rentalInfo.equivalentDailyRent">
            <!-- <el-input-number :controls="false" v-model="data.rentalInfo.equivalentDailyRent" placeholder="请输入折合日租金" /> -->
            <el-input v-model="data.rentalInfo.equivalentDailyRent" placeholder="请输入折合日租金" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="递增日期" prop="rentalInfo.incrementDate">
            <el-input v-model="data.rentalInfo.incrementDate" placeholder="请输入递增日期" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="递增倒计时" prop="rentalInfo.increasingCountdown">
            <el-input v-model="data.rentalInfo.increasingCountdown" placeholder="请输入递增倒计时" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="递增标准" prop="rentalInfo.incrementalCriterion">
            <el-input v-model="data.rentalInfo.incrementalCriterion" placeholder="请输入递增标准" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="电费标准" prop="rentalInfo.electricityRateStandard">
            <el-input v-model="data.rentalInfo.electricityRateStandard" :controls="false" placeholder="请输入电费标准" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="水费标准" prop="rentalInfo.waterTariff">
            <el-input v-model="data.rentalInfo.waterTariff" :controls="false" placeholder="请输入水费标准" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="退&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;租" prop="rentalInfo.rentOutStatus">
            <el-select v-model="data.rentalInfo.rentOutStatus" placeholder="请选择退租状态">
              <el-option
                v-for="dict in park_surrender_tenancy_status"
                :key="`surrender_tenancy_status_${dict.label}`"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="退租时间" prop="rentalInfo.rentOutTime">
            <el-date-picker v-model="data.rentalInfo.rentOutTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <div style="font-size: 10px; padding-top: 10px">
            注意：选择退租后，基础信息中的房间状态变为空置房，租赁信息及收租计划将清空，您可在历史租赁信息查看！
          </div>
        </el-col>
      </el-row>
      <template v-if="data.basicInfo.leaseStatus === 'leased' || dialogOptions.type == 'history'">
        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2>收租信息</h2>
        </div>
        <div v-if="data.rentCollectionPlan == null || data.rentCollectionPlan.length === 0" style="text-align: right">
          <el-button type="primary" @click="createRentCollectionPlan">辅助生成</el-button>
        </div>
        <h2 class="mb-5" style="text-align: center; font-weight: bold">收租计划信息</h2>
        <el-table :data="data.rentCollectionPlan" style="width: 100%" :show-summary="true" :summary-method="getSummaries">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="dueDate" label="应收日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.dueDate" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>

          <el-table-column prop="rentReceivable" label="应收租金(元)">
            <template #default="scope">
              <el-input v-model="scope.row.rentReceivable" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="collect" label="是否收取" width="160">
            <template #default="scope">
              <el-radio-group v-model="scope.row.collect">
                <el-radio :value="false" size="large">否</el-radio>
                <el-radio :value="true" size="large">是</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="paidInTime" label="实收日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.paidInTime" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>
          <el-table-column prop="agent" label="经办人" width="160">
            <template #default="scope">
              <el-input v-model="scope.row.agent" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="160">
            <template #default="scope">
              <el-input v-model="scope.row.remark" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column width="110" label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <div v-if="dialogOptions.type !== 'view' && dialogOptions.type !== 'history'">
                <el-button link type="primary" @click="handleAdd(scope.$index)"> 新增 </el-button>
                <el-button link type="danger" @click="deleteRentCollectionPlan(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div v-if="data.basicInfo.leaseStatus !== 'leased' && dialogOptions.type != 'history'" style="margin: 32px 0">
        <el-empty description="请将租赁状态修改为已租赁以添加租赁信息和收租计划" />
      </div>
    </el-form>

    <template v-if="dialogOptions.type !== 'view' && dialogOptions.type !== 'history'" #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="formSubmit"> 保 存 </el-button>
        <el-button @click="dialogOptions.visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" name="SystemRoleForm" setup>
import {
  getHousepropertyInformation,
  addHousepropertyInformation,
  updateHousepropertyInformation
} from '@/api/zichanguanli/housepropertyInformation/index';
import { getHosuerental, addHosuerental, updateHosuerental } from '@/api/zichanguanli/hosuerental';
import { generateRentPlan, generateSingleRentPlan } from '@/utils/genRentProject';
import {
  listHouseRentCollectionPlan,
  createHouseRentCollectionPlan,
  updateHouseRentCollectionPlan,
  deleteHouseRentCollectionPlan
} from '@/api/zichanguanli/houseRentCollectionPlan';
import { validateNumber, validateInteger } from '@/utils/formRules';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { parkbuilingroom_state, parkr_building_room_environment, park_surrender_tenancy_status, park_frent_payment_frequency } = toRefs<any>(
  proxy?.useDict('parkbuilingroom_state', 'parkr_building_room_environment', 'park_surrender_tenancy_status', 'park_frent_payment_frequency')
);

const formRules = reactive({
  'basicInfo.propertyName': [{ required: true, message: '请输入房产名称', trigger: 'blur' }],
  'basicInfo.floorArea': [{ validator: validateNumber, trigger: ['blur', 'change'] }],
  'basicInfo.propertyValuation': [{ validator: validateNumber, trigger: ['blur', 'change'] }],
  'basicInfo.leaseStatus': [{ required: true, message: '请选择租赁状况', trigger: 'change' }],
  'rentalInfo.name': [{ required: true, message: '承租人不能为空', trigger: 'blur' }],
  'rentalInfo.contactInformation': [{ required: true, message: '联系方式不能为空', trigger: 'blur' },
    {  required: true, message: '请填写正确的手机号码', trigger: 'change' }],
  'rentalInfo.frentPaymentFrequency': [{ required: true, message: '请选择缴租频次', trigger: 'change' }],
  'rentalInfo.rentRegulation': [{ required: true, message: '请输入租金规定', trigger: 'blur' }],
  'rentalInfo.startTime': [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  'rentalInfo.endTime': [{ required: true, message: '请选择结束时间', trigger: 'change' }]
});

const emits = defineEmits(['refresh']);

const dialogOptions = reactive({
  visible: false,
  loading: false,
  type: null
});

const houseFormRef = ref(null);

const dialogTitle = computed(() => {
  switch (dialogOptions.type) {
    case 'create':
      return '新建房产（其他）信息';
    case 'edit':
      return '编辑房产（其他）信息';
    case 'view':
      return '房产（其他）信息详情';
    case 'history':
      return '房产（其他）历史信息详情';
    default:
      return '房产（其他）信息';
  }
});

const basicPropertyInformationOpenId = ref(null);
const houseRentalIOpenId = ref(null);
const isHistory = ref(null);

const data = reactive({
  basicInfo: {
    id: null,
    primarySinglet: undefined,
    propertyName: undefined,
    type: undefined,
    propertyLocation: undefined,
    doorNumber: undefined,
    floorArea: undefined,
    realEstateRegistrationNumber: undefined,
    propertyValuation: undefined,
    leaseStatus: undefined
  },
  rentalInfo: {
    id: undefined,
    name: undefined,
    associate: undefined,
    contactInformation: undefined,
    leaseholdArea: undefined,
    termContract: undefined,
    startTime: undefined,
    endTime: undefined,
    remainingDays: undefined,
    contractNumber: undefined,
    rentRegulation: undefined,
    appraisedAnnualRent: undefined,
    incrementDate: undefined,
    increasingCountdown: undefined,
    incrementalCriterion: undefined,
    electricityRateStandard: undefined,
    waterTariff: undefined,
    houseId: undefined,
    rentOutStatus: undefined,
    equivalentDailyRent: undefined,
    frentPaymentFrequency: undefined,
    rentOutTime: undefined
  },
  rentCollectionPlan: [] // 初始化为一个空数组
});

const originalLeaseStatus = ref('');

const formDialogDataInit = async () => {
  try {
    const params = {
      basicPropertyInformationId: basicPropertyInformationOpenId.value,
      houseRentalId: houseRentalIOpenId.value,
      isHistory: isHistory.value
    };
    const res = await getHousepropertyInformation(params);
    originalLeaseStatus.value = res.data.basicPropertyInformationVo.leaseStatus;
    data.basicInfo = res.data.basicPropertyInformationVo;
    data.rentalInfo = res.data.houseRentalVo || {};
    data.rentCollectionPlan = res.data.rentCollectionPlanVo || [];
    // const rentalInfoRes = await getHosuerental(basicPropertyInformationId.value);
    // const rentCollectionPlanRes = await listHouseRentCollectionPlan({ basicPropertyInformationId: basicPropertyInformationId.value });

    // for (const key in data.basicInfo) {
    //   data.basicInfo[key] = basicInfoRes.data[key];
    // }

    // for (const key in data.rentalInfo) {
    //   data.rentalInfo[key] = rentalInfoRes.data[key];
    // }

    // data.rentCollectionPlan = rentCollectionPlanRes.rows;
  } catch (error) {
    proxy?.$modal.msgError(`数据加载失败，${error}`);
  }
};

const formReset = async () => {
  for (const key in data.basicInfo) {
    data.basicInfo[key] = undefined;
  }

  data.basicInfo.leaseStatus = 'in_idle';
  originalLeaseStatus.value = 'in_idle';

  for (const key in data.rentalInfo) {
    data.rentalInfo[key] = undefined;
  }

  data.rentCollectionPlan = [];
};

const formSubmit = async () => {
  const valid = await houseFormRef.value.validate();
  if (!valid) return;
  try {
    dialogOptions.loading = true;
    switch (dialogOptions.type) {
      case 'create':
        const datas = {
          basicPropertyInformationBo: data.basicInfo,
          houseRentalBo: data.rentalInfo,
          rentCollectionPlanBo: data.rentCollectionPlan
        };
        await addHousepropertyInformation(datas);
        // basicPropertyInformationId.value = basicInfoRes.data;
        // await addHosuerental({ ...data.rentalInfo, houseId: basicPropertyInformationId.value });

        // if (data.rentCollectionPlan.length) {
        //   data.rentCollectionPlan.map(async (item) => {
        //     item.basicPropertyInformationId = basicPropertyInformationId.value;
        //     await createHouseRentCollectionPlan(item);
        //   });
        // }

        break;
      case 'edit':
        const dataArr = {
          basicPropertyInformationBo: data.basicInfo,
          houseRentalBo: data.rentalInfo,
          rentCollectionPlanBo: data.rentCollectionPlan
        };
        await updateHousepropertyInformation(dataArr);
        // if (data.rentalInfo.id != null) {
        //   await updateHosuerental({ ...data.rentalInfo });
        // } else {
        //   await addHosuerental({ ...data.rentalInfo, houseId: basicPropertyInformationId.value });
        // }

        // if (data.rentCollectionPlan.length) {
        //   data.rentCollectionPlan.map(async (item) => {
        //     item.basicPropertyInformationId
        //       ? await updateHouseRentCollectionPlan(item)
        //       : await createHouseRentCollectionPlan({ ...item, basicPropertyInformationId: basicPropertyInformationId.value });
        //   });
        // }
        break;
    }
    emits('refresh');
  } catch (error) {
    proxy?.$modal.msgError(`数据提交失败，${error}`);
  } finally {
    dialogOptions.loading = false;
    dialogOptions.visible = false;
  }
};

const createRentCollectionPlan = () => {
  if (!data.rentalInfo.frentPaymentFrequency || !data.rentalInfo.rentRegulation || !data.rentalInfo.startTime || !data.rentalInfo.endTime) {
    proxy?.$modal.msgError('请先完善租赁信息中的必填项');
    return;
  }

  const params = {
    frequencyOfRentPayments: data.rentalInfo.frentPaymentFrequency,
    rents: data.rentalInfo.rentRegulation,
    startTime: data.rentalInfo.startTime,
    endTime: data.rentalInfo.endTime,
    transform: false
  };

  data.rentCollectionPlan = generateRentPlan(params);
};

const deleteRentCollectionPlan = async (index: number, row: any) => {
  if (row.id) {
    await deleteHouseRentCollectionPlan(row.id);
    data.rentCollectionPlan.splice(index, 1);
  } else {
    data.rentCollectionPlan.splice(index, 1);
  }
};

const handleAdd = (index: number) => {
  const newPlan = generateSingleRentPlan();
  if (!data.rentCollectionPlan) {
    data.rentCollectionPlan = [];
  }
  data.rentCollectionPlan.splice(index + 1, 0, newPlan);
};

const open = async (type: string, basicPropertyId: string | number, houseRentalargsId: string | number) => {
  dialogOptions.type = type;
  dialogOptions.visible = true;
  dialogOptions.loading = true;
  nextTick(() => formReset());
  switch (dialogOptions.type) {
    case 'edit':
    case 'view':
      basicPropertyInformationOpenId.value = basicPropertyId;
      houseRentalIOpenId.value = houseRentalargsId;
      isHistory.value = false;
      await formDialogDataInit();
      break;
    case 'history':
      basicPropertyInformationOpenId.value = basicPropertyId;
      houseRentalIOpenId.value = houseRentalargsId;
      isHistory.value = true;
      await formDialogDataInit();
      break;
  }
  console.log('data', data);
  dialogOptions.loading = false;
};

const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (index === 2) {
      // 应收租金列的索引
      const values = data.map((item: any) => Number(item.rentReceivable) || 0);
      sums[index] = values.reduce((prev: number, curr: number) => {
        return prev + curr;
      }, 0);
      // 格式化数字，保留2位小数
      sums[index] = sums[index].toFixed(2);
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 添加 watch 来监听租赁状态的变化
watch(
  () => data.basicInfo.leaseStatus,
  (newValue) => {
    if (newValue !== 'leased' && dialogOptions.type != 'history' && dialogOptions.type != 'detail') {
      // 如果切换到非已出租状态，清空租赁信息和收租计划
      data.rentalInfo = {
        id: undefined,
        name: undefined,
        associate: undefined,
        contactInformation: undefined,
        leaseholdArea: undefined,
        termContract: undefined,
        startTime: undefined,
        endTime: undefined,
        remainingDays: undefined,
        contractNumber: undefined,
        rentRegulation: undefined,
        appraisedAnnualRent: undefined,
        incrementDate: undefined,
        increasingCountdown: undefined,
        incrementalCriterion: undefined,
        electricityRateStandard: undefined,
        waterTariff: undefined,
        houseId: undefined,
        rentOutStatus: undefined,
        equivalentDailyRent: undefined,
        frentPaymentFrequency: undefined,
        rentOutTime: undefined
      };
      data.rentCollectionPlan = [];
    }
    if (newValue === 'leased' && dialogOptions.type != 'history' && dialogOptions.type != 'detail') {
      data.rentalInfo.rentOutStatus = 'under_rent'; // 设置为在租状态
    }
  }
);

defineExpose({ open });
</script>
